/*
* Copyright 2011 Pavel Kozhin 
*
* Licensed under the Apache License, Version 2.0 (the "License"); 
* you may not use this file except in compliance with the License. 
* You may obtain a copy of the License at 
* 
* http://www.apache.org/licenses/LICENSE-2.0
* 
* Unless required by applicable law or agreed to in writing, software 
* distributed  under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
* See the License for the specific language governing permissions and 
* limitations under the License.
*
* Author: Pavel Kozhin.
*/
package org.etherframework.dependency
{
	import org.etherframework.core.bridge.IBridge;
	import org.etherframework.core.bridge.IObjectController;
	import org.etherframework.core.context.Context;
	
	public final class Dependency
	{
		private var _key:Class;
		private var _value:*;
		private var _isGenerator:Boolean;
		private var _isSingleton:Boolean;
		private var _bridge:IBridge;
		private var _context:Context;
		private var _destroyed:Boolean;
		
		public function Dependency(key:Class, value:*, isGenerator:Boolean, 
								   isSingleton:Boolean, bridge:IBridge, context:Context)
		{
			_key = key;
			_value = value;
			_isGenerator = isGenerator;
			_isSingleton = isSingleton;
			_bridge = bridge;
			_context = context;
		}
		
		public function getInstance(context:Context = null):Object
		{
			if (_destroyed)
				return null;
			
			var instance:Object;
			var ctx:Context = (context && _context.equals(context)) ? 
				context : _context;
			
			if (_value is Class)
			{
				instance = _bridge.process(_value, _bridge.createEther(ctx));
				
				if (instance is IObjectController)
					instance = IObjectController(instance).target;
				
				if (_isSingleton)
					_value = instance;
				
				return instance;
			}
			
			if (_isSingleton)
				return _value;
			
			if (!_bridge.hasController(_value))
			{
				instance = _bridge.process(_value, _bridge.createEther(ctx));
				
				if (instance is IObjectController)
					instance = IObjectController(instance).target;
				
				return instance;
			}
			
			return _value;
		}
		
		public function get type():Class { return _key; }
	}
}